package be.novelfaces.component.numpaddecsep;

import static be.novelfaces.component.util.js.JS.SCRIPT;
import static be.novelfaces.component.util.js.JS.TEXT_JAVASCRIPT;
import static be.novelfaces.component.util.js.JS.TYPE;

import java.io.IOException;
import java.text.DecimalFormatSymbols;
import java.util.Locale;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;

import be.novelfaces.component.encoder.Encoder;
import be.novelfaces.util.StringUtils;

public class NumpadDecimalSeparatorJSEncoder implements Encoder {

	static final String SEPARATOR = "separator";

	public void encode(FacesContext context, UIComponent component)
			throws IOException {
		ResponseWriter writer = context.getResponseWriter();
		writer.startElement(SCRIPT.getName(), null);
		writer.writeAttribute(TYPE.getName(), TEXT_JAVASCRIPT.getName(), null);
		writer.write("new NovelFaces.numpadDecSeparator(\""
				+ component.getClientId() + "\", {");
		writer.write(SEPARATOR + ":\"" + getSeparator(context, component) + "\"");
		writer.write("});");
		writer.endElement(SCRIPT.getName());
	}

	private String getSeparator(FacesContext context, UIComponent component) {
		if (StringUtils.isEmpty((String) component.getAttributes().get(
				SEPARATOR))
				|| component.getAttributes().get(SEPARATOR) == "DEFAULT") {
			return getDecimalSeparatorFromLocaleFromViewRoot(context);
		}
		return (String) component.getAttributes().get(SEPARATOR);
	}

	private String getDecimalSeparatorFromLocaleFromViewRoot(
			FacesContext context) {
		Locale locale = context.getViewRoot().getLocale();
		return String.valueOf(DecimalFormatSymbols.getInstance(locale)
				.getDecimalSeparator());
	}

}
